package gofire

import (
	"gofire/utils"
	"net/http"
	"path"
)

type Group struct {
	parent      *Group
	prefix      string
	fullPrefix  string
	server      *HttpServer
	middlewares []Middleware
}

func (group *Group) NewGroup(prefix string) *Group {
	return &Group{
		parent:      group,
		prefix:      prefix,
		fullPrefix:  path.Join(group.fullPrefix, prefix),
		server:      group.server,
		middlewares: make([]Middleware, 0),
	}
}

func (group *Group) url(url string) string {
	return utils.JoinPaths(group.fullPrefix, url)
}

func (group *Group) handleRequest(method, url string, handleFunc HandleFunc) {
	completeUrl := group.url(url)

	for _, middleware := range group.middlewares {
		handleFunc = middleware(handleFunc)
	}

	switch method {
	case "GET":
		group.server.Get(completeUrl, handleFunc)
	case "POST":
		group.server.Post(completeUrl, handleFunc)
	case "PUT":
		group.server.Put(completeUrl, handleFunc)
	case "DELETE":
		group.server.Delete(completeUrl, handleFunc)
	}
}

func (group *Group) Get(url string, handleFunc HandleFunc) {
	group.handleRequest(http.MethodGet, url, handleFunc)
}

func (group *Group) Post(url string, handleFunc HandleFunc) {
	group.handleRequest(http.MethodPost, url, handleFunc)
}

func (group *Group) Put(url string, handleFunc HandleFunc) {
	group.handleRequest(http.MethodPut, url, handleFunc)
}

func (group *Group) Delete(url string, handleFunc HandleFunc) {
	group.handleRequest(http.MethodDelete, url, handleFunc)
}

func (group *Group) Use(middlewares ...Middleware) {
	group.middlewares = append(group.middlewares, middlewares...)
}
